package com.ruoyi.framework.config.MybatisPlus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        LoginUser user = SecurityUtils.getLoginUser();
        if (user != null && user.getUser() != null) {
            this.strictInsertFill(metaObject, "createBy", String.class, user.getUsername());
            this.strictInsertFill(metaObject, "createById", Long.class, user.getUserId());
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        LoginUser user = SecurityUtils.getLoginUser();
        if (user != null && user.getUser() != null) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, user.getUsername());
            this.strictUpdateFill(metaObject, "updateById", Long.class, user.getUserId());
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}
